package com.jayson.server;

import com.jayson.server.catalina.Host;
import com.jayson.server.catalina.Mapper;
import org.dom4j.DocumentException;

import java.util.List;
import java.util.concurrent.*;

public class Bootstrap {

    private Mapper mapper = null;

    public static void main(String[] args) {

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.load();
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化mapper
     * @throws DocumentException
     */
    private void load() throws DocumentException {
        if(this.mapper == null) {
            this.mapper = new Mapper();
            mapper.init("server.xml");
        }
    }


    /**
     * 启动容器
     * @throws Exception
     */
    public void  start() throws Exception {
        // 初始化线程池对象
        int corePoolSize = 10;
        int maximumPoolSize = 100;
        long keepAliveTime = 5;
        TimeUnit unit = TimeUnit.MINUTES;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(corePoolSize);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

        // 通过线程来监控不同的端口
        for(String port : mapper.getPortMap().keySet()){
            List<Host> hosts = mapper.getPortMap().get(port);
            new Thread(new SocketThread(Integer.valueOf(port), threadPoolExecutor, hosts)).start();
        }

    }
}
